package com.online.shopping.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.online.shopping.entity.RespBean;
import com.online.shopping.entity.ResultPage;
import com.online.shopping.pojo.TbBrand;
import com.online.shopping.service.GoodBrandsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/goodBrands_Ms")
public class GoodBrandsController {

	@Autowired
	private GoodBrandsService goodBrandsService;

	@GetMapping("/findAll")
	public ResultPage findAll(int pageNum, int pageSize){
		System.out.println("页码："+pageNum);
		System.out.println("每页记录数："+pageSize);

		PageHelper.startPage(pageNum, pageSize);
		Page<TbBrand> page = (Page<TbBrand>) goodBrandsService.findAllTbBrandByPage();

		ResultPage resultPage = new ResultPage();
		resultPage.setRows(page.getResult());
		resultPage.setTotal(page.getTotal());

		return resultPage;
	}

	@GetMapping("/findBrandById/{id}")
	public TbBrand findBrandById(@PathVariable Long id){
		return goodBrandsService.findTbBrandById(id);
	}

	@PostMapping("/add")
	public RespBean add(@RequestBody TbBrand brand){
		System.out.println("brand id: "+brand.getId());
		System.out.println("brand title: "+brand.getName());

		try{
			goodBrandsService.addTbBrand(brand);
			return RespBean.ok("添加成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("添加失败！");
		}
	}

	@PostMapping("/update")
	public RespBean update(@RequestBody TbBrand brand){
		System.out.println("brand id: "+brand.getId());
		System.out.println("brand title: "+brand.getName());

		try{
			goodBrandsService.updateTbBrand(brand);
			return RespBean.ok("修改成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("修改失败！");
		}
	}

	@PostMapping("/delete")
	public RespBean delete(@RequestBody Long[] ids){
		System.out.println("id[]: "+ids);

		try{
			goodBrandsService.delete(ids);
			return RespBean.ok("删除成功！");
		} catch (Exception e){
			e.printStackTrace();
			return RespBean.error("删除失败！");
		}
	}

	@GetMapping("/findBrandList")
	public List findBrandList(){
		return goodBrandsService.findBrandList();
	}
}
